package com.example.itcacp.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

@Component
public class SensitiveWordFilter {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveWordFilter.class);
    private static final Set<String> sensitiveWords = new HashSet<>();

    private final String filePath;

    public SensitiveWordFilter(@Value("${sensitive.words.file.path}") String filePath) {
        this.filePath = filePath;
        logger.info("敏感词文件路径: {}", filePath);
    }

    @PostConstruct
    private void init() {
        try {
            loadSensitiveWords();
            logger.info("成功加载敏感词，共 {} 个", sensitiveWords.size());
        } catch (Exception e) {
            logger.error("加载敏感词文件失败: {}", e.getMessage(), e);
            throw new RuntimeException("加载敏感词文件失败", e);
        }
    }

    private void loadSensitiveWords() throws IOException {
        logger.debug("尝试加载敏感词文件: {}", filePath);

        // 验证文件是否存在
        if (!new ClassPathResource(filePath).exists()) {
            logger.error("敏感词文件不存在: {}", filePath);
            throw new IOException("敏感词文件不存在: " + filePath);
        }

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(new ClassPathResource(filePath).getInputStream()))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    sensitiveWords.add(line.trim());
                }
            }
        }
    }

    // 检查是否包含敏感词
    public boolean containsSensitiveWord(String content) {
        if (content == null) return false;
        for (String word : sensitiveWords) {
            if (content.contains(word)) {
                return true;
            }
        }
        return false;
    }

    // 替换敏感词
    public String filterSensitiveWords(String content) {
        if (content == null) return null;
        String result = content;
        for (String word : sensitiveWords) {
            result = result.replace(word, "***");
        }
        return result;
    }
}